<template>
  <div class="video">
    <el-card>
      <div slot="header">
        <div class="title">课程：{{ course.courseName }}</div>
        <div class="title">阶段：{{ course.sectionName }}</div>
        <div class="title">课时：{{ course.lessonName }}</div>
      </div>
      <el-form label-width="40px">
        <el-form-item class="video-upload" label="视频">
          <el-progress
            v-if="isVedioUploading"
            type="circle"
            :percentage="vedioPercentage"
            :width="100"
            :status="isVedioUploadSuccess ? 'success' : undefined"
          />
          <input
            ref="video-file"
            type="file"
            @change="onchange"
          >
          <el-button v-if="!isVedioUploading">+ 选择视频</el-button>
        </el-form-item>
        <el-form-item v-if="videoPath" class="video-upload" label="路径">
          <div>{{ videoPath }}</div>
        </el-form-item>
        <el-form-item class="image-upload" label="封面">
          <input
            ref="image-file"
            type="file"
            @change="onchange($event, true)"
          />
          <el-button v-if="!imageUrl">+选择封面</el-button>
          <img v-else :src="imageUrl">
        </el-form-item>
        <el-form-item v-if="imagePath" class="video-upload" label="路径">
          <span>{{ imagePath }}</span>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="authUpload"
            style="marginLeft: 40px"
          >开始上传</el-button>
          <el-button @click="backRoute">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script>
/* eslint-disable */
import axios from 'axios'
import {
  aliyunImagUploadAddressAdnAuth,
  aliyunVideoUploadAddressAdnAuth,
  transCodeVideo,
  getAliyunTransCodePercent
} from '@/services/aliyun-oss'
import { getMediaByLessonId } from "@/services/course-lesson"

export default {
  data () {
    return {
      uploader: null,
      videoId: null,
      imageUrl: '',
      fileName: '',
      videoFile: null,
      videoPath: '',
      imagePath: '',
      isVedioUploading: false,
      vedioPercentage: 0,
      course: {
        courseName: this.$route.query.courseName,
        sectionName: this.$route.query.sectionName,
        lessonName: this.$route.query.lessonName
      }
    }
  },
  created () {
    this.getCourse()
    this.initUploader()
  },
  computed: {
    video () {
      return this.$refs['video-file']
    },
    image () {
      return this.$refs['image-file']
    },

    isVedioUploadSuccess () {
      return this.vedioPercentage === 100
    }
  },
  methods: {
    backRoute () {
      history.back()
      // /course/1491/section
    },
    async getCourse () {
      const { data } = await getMediaByLessonId(this.$route.query.lessonId)
      this.imageUrl = data.data.coverImageUrl
      this.videoPath = data.data.fileName
    },
    onchange ($event, isImage) {
      console.log($event)
      if(!isImage){
        this.isVedioUploading = false
        this.videoFile = $event.target.files[0]
        this.videoPath = $event.target.value
      } else {
        const file = $event.target.files[0]

        var reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onloadstart = function () {
            console.log('图片正在上传处理......')
        };
        //操作完成
        reader.onload = (e) => {
            // file 对象的属性
            // elem.setAttribute('src', reader.result)
            this.imageUrl = reader.result
        }
        this.imagePath = $event.target.value
      }
    },
    authUpload () {
      if(this.videoFile){
        this.vedioPercentage = 0
        this.isVedioUploading = true
        this.videoPath = '正在上传视频，请勿关闭页面~'
        this.imagePath = '正在上传图片~'

        const videoFile = this.video.files[0]
        const imageFile = this.image.files[0]
        const uploader = this.uploader
        // 要确保封面先上传
        uploader.addFile(imageFile, null, null, null, '{"Vod":{}}')
        uploader.addFile(videoFile, null, null, null, '{"Vod":{}}')
        uploader.startUpload()
        this.fileName = videoFile.name
      } else {
        this.$message({type: 'error', message: '请选择视频或图片！'})
      }
    },
    initUploader () {
      this.uploader = new window.AliyunUpload.Vod({
        // 阿里账号ID，必须有值 ，值的来源https://help.aliyun.com/knowledge_detail/37196.html
        userId: 1618139964448548,
        // 上传到点播的地域， 默认值为'cn-shanghai',//eu-central-1,ap-southeast-1
        region: 'cn-shanghai',
        // 分片大小默认1M，不能小于100K
        partSize: 1048576,
        // 并行上传分片个数，默认5
        parallel: 5,
        // 网络原因失败时，重新上传次数，默认为3
        retryCount: 3,
        // 网络原因失败时，重新上传间隔时间，默认为2秒
        retryDuration: 2,
        // 开始上传
        onUploadstarted: async uploadInfo => {
          console.log('onUploadstarted', uploadInfo)

          let uploadAuthInfo = null
          if (uploadInfo.isImage) {
            const { data } = await aliyunImagUploadAddressAdnAuth()
            this.imageUrl = data.data.imageURL
            uploadAuthInfo = data.data
          } else {
            const { data } = await aliyunVideoUploadAddressAdnAuth({
              fileName: uploadInfo.file.name,
              imageUrl: this.imageUrl // 要确保封面先上传
            })
            this.videoId = data.data.videoId
            uploadAuthInfo = data.data
          }
          
          // console.log('uploadAuthInfo', uploadAuthInfo)
          this.uploader.setUploadAuthAndAddress(
            uploadInfo,
            uploadAuthInfo.uploadAuth,
            uploadAuthInfo.uploadAddress,
            uploadAuthInfo.videoId || uploadAuthInfo.imageId
          )
        },
        // 文件上传成功
        onUploadSucceed: function (uploadInfo) {
          console.log('onUploadSucceed', uploadInfo)
        },
        // 文件上传失败
        onUploadFailed: function (uploadInfo, code, message) {
          console.log('onUploadFailed')
        },
        // 文件上传进度，单位：字节
        onUploadProgress: (uploadInfo, totalSize, loadedPercent) => {
          if (!uploadInfo.isImage) {
            this.vedioPercentage = Math.floor(loadedPercent * 100)
            console.log('loadedPercent', this.vedioPercentage)
          }
          else {
            const percent = Math.floor(loadedPercent * 100)
            this.imagePath = '图片已上传：' + percent + '%'
          }
        },
        // 上传凭证超时
        onUploadTokenExpired: function (uploadInfo) {
          console.log('onUploadTokenExpired')
        },
        // 全部文件上传结束
        onUploadEnd: async uploadInfo => {
          this.videoPath = '正在转码中，请勿关闭页面！转码进度：0%'
          console.log('onUploadEnd:', uploadInfo)
          console.log('onUploadEnd obj:', {
            lessonId: this.$route.query.lessonId,
            fileId: this.videoId,
            coverImageUrl: this.imageUrl,
            fileName: this.fileName
          })

          const { data } = await transCodeVideo({
            lessonId: this.$route.query.lessonId,
            fileId: this.videoId,
            coverImageUrl: this.imageUrl,
            fileName: this.fileName
          })
          console.log('请求转码，data:', data)

          const timer = setInterval(async () => {
            const { data } = await getAliyunTransCodePercent(this.$route.query.lessonId)
            console.log('转码进度', data)
            this.videoPath = `正在转码中，请勿关闭页面！转码进度：${data.data}%`
            if(data.data === 100){
              window.clearInterval(timer)
              this.videoPath = `转码成功！`
              this.$message({type: 'success', message: '视频上传和转码成功！'})
            }
          }, 3000)
        }
      })
    }
  }
}
</script>
<style lang="scss">
.video{
  .title{
    padding: 20px 0;
  }

  .video-upload,.image-upload{
    display: flex;
    align-items: center;
    position: relative;

    input{
      width: 100px;
      height: 100px;
      opacity: 0;
      position: absolute;
      top: 0;
      left: 0;
      z-index: 1;
    }

    .el-button{
      width: 100px;
      height: 100px;
      padding: 0;
    }

    .el-progress{
      width: 100px;
      height: 100px;
    }

    img{
      width: 100px;
      height: 100px;;
    }
  }

  .image-upload{
    .el-form-item__content{
      height: 100px;
    }
  }
}
</style>
